<template>
  <div class="overflow-y-auto font-normal text-sm min-h-[244px]">
    <!-- 银行卡列表 -->
    <template v-if="showBanckDeit == 'bankList'">
      <div
        class="myBanck px-[6px] rounded-lg bg-[#2f4553] py-[8px] mb-[6px] w-full"
        v-for="(item, index) in bankDataList"
      >
        <div class="weight">{{ item.bank_name }}</div>
        <div class="flex justify-between font-normal w-full mt-2">
          <div class="text-[12px] text-[#c9d1e4] overflow-wrap_text">
            {{ item.bank_card_number }}
          </div>
          <div class="mr-[12px] flex">
            <div
              class="bg-[#426073] p-[4px] rounded ml-[16px] h-[24px]"
              @click.stop="removeBanck(item, index)"
            >
              <svg-icon
                class="text-[14px] text-[#d9d9d9] group-hover:text-white"
                name="delete"
              />
            </div>
          </div>
        </div>
        <div
          class="text-[12px] text-[#c9d1e4] font-normal mt-2 overflow-wrap_text"
        >
          {{ item.holder_name }}
        </div>
      </div>
    </template>

    <!-- 银行卡提现输入 -->
    <template v-if="showBanckDeit == 'bankDetails'">
      <div
        class="p-2 Warning text-[#ff9203] md:text-sm rounded-sm mb-2"
        v-if="warningTip == '1'"
      >
        {{ $t("layer.wallet.moreDetails") }}
      </div>
      <div class="bg-[#2f4553] rounded-lg p-2 pt-5">
        <div class="flex justify-between mt-1">
          <div>
            {{ $t("layer.wallet.withdrawalBankCard") }}
          </div>
          <div class="text-[#1475e1]" @click="addBanckData">
            {{ $t("layer.wallet.addBankCard") }}
          </div>
        </div>
        <div class="mt-1">
          <div>
            <el-select
              v-model="selectVal"
              placeholder=""
              size="large"
              @change="changeVal"
              style="width: 100%"
              popper-class="mySelectStyle"
            >
              <el-option
                v-for="item in bankDataList"
                :key="item.bank_card_id"
                :label="item.bank_name"
                :value="item.bank_card_id"
              />
            </el-select>
          </div>
        </div>

        <div class="flex mt-5 justify-between">
          <div>
            {{ $t("layer.wallet.withdrawalAmount") }}
          </div>
        </div>
        <div class="mt-1 amnit">
          <el-input v-model="walletInfo" @input="changeInputVal">
            <template #prefix>
              <span class="text-[#fff]">{{ main.currency }}</span>
            </template>
          </el-input>
        </div>

        <div class="text-sm text-[#c9d1e4] flex justify-between mt-2 mb-3">
          <div>{{ $t("layer.wallet.WithdrawableMony") }}:{{ balance }}</div>
          <div>
            {{ $t("layer.wallet.auditRequirements") }}：{{
              walletMony.freeze_amount
            }}
          </div>
        </div>

        <div class="bg-[#426073] h-[1px]"></div>

        <div class="mt-4 text-sm font-thin leading-6 text-[#b1bad3]">
          <p>
            {{ $t("layer.wallet.lowerlimit") }}:
            {{ walletDetil?.once_min_limit }} -
            {{ walletDetil?.once_max_limit }}
          </p>
          <p>
            {{ $t("layer.wallet.freewithdrawals") }}:
            {{ walletDetil?.remaining_free_count }}
          </p>
          <p>
            {{ $t("layer.wallet.RemainingTimes") }}:
            {{
              walletDetil?.withdraw_day_count == 0
                ? $t("layer.wallet.nolimit")
                : walletDetil?.withdraw_day_count
            }}
          </p>
        </div>

        <div class="w-full flex justify-center h-full mt-6">
          <button
            class="h-8 bg-[#1475e1] w-full rounded-md"
            @click="submitReview"
          >
            {{ $t("layer.wallet.submitReview") }}
          </button>
        </div>
      </div>
    </template>

    <!-- 提现稽核页面 -->
    <template v-if="showBanckDeit == 'withdrawalAudit'">
      <div class="p-4 text-sm bg-[#2f4553] rounded">
        <div>
          {{ $t("layer.wallet.withdrawalBankCard") }}
        </div>
        <table
          class="w-full border-collapse border border-[#426073] mt-4 text-white text-center"
        >
          <tr class="">
            <td class="border border-[#426073] p-2">
              {{ $t("layer.wallet.table1") }}
            </td>
            <td class="border border-[#426073] p-2 text-green-500">
              {{ previewData.amount }} {{ main.currency }}
            </td>
          </tr>
          <tr class="">
            <td class="border border-[#426073] p-2">
              {{ $t("layer.wallet.table2") }}
            </td>
            <td class="border border-[#426073] p-2 text-green-500">
              {{ previewData.not_audited_amount }} {{ main.currency }}
            </td>
          </tr>
          <tr class="">
            <td class="border border-[#426073] p-2">
              {{ $t("layer.wallet.table3") }}
            </td>
            <td class="border border-[#426073] p-2 text-green-500">
              {{ previewData.exempt_audited_amount }} {{ main.currency }}
            </td>
          </tr>
          <tr class="">
            <td class="border border-[#426073] p-2">
              {{ $t("layer.wallet.table4") }}({{ previewData.bank_fee.rate }}%)
            </td>
            <td class="border border-[#426073] p-2 text-green-500">
              {{ previewData.bank_fee.amount }} {{ main.currency }}
            </td>
          </tr>
          <tr class="">
            <td class="border border-[#426073] p-2">
              {{ $t("layer.wallet.table5") }}({{ previewData.admin_fee.rate }}%)
            </td>
            <td class="border border-[#426073] p-2 text-green-500">
              {{ previewData.admin_fee.amount }} {{ main.currency }}
            </td>
          </tr>
          <tr class="">
            <td class="border border-[#426073] p-2">
              {{ $t("layer.wallet.table6") }}
            </td>
            <td class="border border-[#426073] p-2 text-green-500">
              {{ previewData.paid_amount }} {{ main.currency }}
            </td>
          </tr>
        </table>
        <div class="flex justify-center mt-8">
          <button
            @click.stop="editBanck('bankDetails', false, null)"
            class="bg-[#4e6b7d] hover:bg-[#1a2c38] text-white text-sm px-8 mr-4 py-2 rounded"
          >
            {{ $t("layer.wallet.cancel") }}
          </button>
          <button
            @click="withdrawVerify"
            class="bg-[#1475e1] hover:bg-[#105eb4] text-sm px-8 text-white py-2 rounded"
          >
            {{ $t("layer.wallet.validate") }}
          </button>
        </div>
      </div>
    </template>

    <!-- 设置支付密码 -->
    <template v-if="showBanckDeit == 'withdrawalPassword'">
      <div class="p-4 text-sm bg-[#2f4553] rounded">
        <withdrawalPwd
          @alterPwd="getAlterPwd"
          @setTicket="getTicket"
        ></withdrawalPwd>
      </div>
    </template>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import {
  bankcardList,
  removeBankcard,
  withdrawPreview,
  withdrawPost,
  getPaymentWithdrawAmountInfo
} from "@/api/wallet.js";
import { showConfirmDialog } from "vant";
import { useI18n } from "vue-i18n";
import { ElNotification } from "element-plus";
import { mainAct } from "@/store/activeda";
import withdrawalPwd from "./withdrawalPwd.vue";
import { mainWallet } from "@/store/wallet";

const setWallet = mainWallet();
const main = mainAct();
const { t } = useI18n();
const dialog = ref(false);
const bankDataList = ref([]);
const getBankcardList = () => {
  bankcardList({
    page: 1,
    page_size: 50
  }).then(res => {
    if (res.data?.list && res.data.list.length) {
      res.data.list.forEach(item => {
        item.bank_number_ = item.bank_card_number.slice(-4);
        item.bank_name = item.bank_name + "(" + item.bank_number_ + ")";
      });
      bankDataList.value = res.data.list;
      selectVal.value = res.data.list[0].bank_card_id;
    }
  });
};

const removeBanck = (item, index) => {
  showConfirmDialog({
    title: t("layer.wallet.unbundling"),
    message: item.bank_name,
    confirmButtonText: t("layer.wallet.confirm"),
    cancelButtonText: t("layer.wallet.cancel")
  })
    .then(async () => {
      let data = {
        bank_card_id: item.bank_card_id
      };
      removeBankcard(data).then((res: any) => {
        console.log(res);
        if (res.errno == 0) {
          ElNotification({
            position: "top-left",
            zIndex: 1015,
            message: t("layer.wallet.operationSuccessful"),
            type: "success"
          });
          bankDataList.value.splice(index, 1);
          getBankcardList();
        }
      });
    })
    .catch(() => {
      // on cancel
    });
};

/**
 * 是否显示银行卡详情
 *  bankList             1.显示银行卡列表
 *  bankDetails          2.显示提现确页面
 *  withdrawalAudit      3.显示提现稽核
 *  withdrawalPassword   4.显示提现密码
 */
const showBanckDeit = ref("bankDetails"); //
const walletInfo = ref("");
const banckItem: any = ref({});

/**
 * 控制父组件显示提现还是tab
 */
const emit = defineEmits(["showMoney", "shoAddbanck"]);

const editBanck = (index, boolend, item) => {
  if (warningTip.value == "1") return;

  showBanckDeit.value = index;
  emit("showMoney", true);
};

const addBanckData = () => {
  emit("shoAddbanck", false);
  showBanckDeit.value = "bankList";
};

const changeVal = val => {
  banckItem.value = bankDataList.value.find(item => item.bank_card_id == val);
};

const selectVal = ref("");

const previewData = ref(null);
const withdrawalOnceToken = ref("");
//提现预览
const submitReview = async () => {
  if (!selectVal.value.toString().length)
    return ElNotification({
      position: "top-left",
      zIndex: 1015,
      message: `${t("layer.wallet.PleaseSelect")}${t(
        "layer.wallet.withdrawalBankCard"
      )}`,
      type: "error"
    });
  if (warningTip.value == "1") return;
  if (changeBalance()) {
    emit("showMoney", false);
    showBanckDeit.value = "withdrawalPassword";
  }
};

const withdrawVerify = async () => {
  let data = {
    withdrawal_once_token: withdrawalOnceToken.value
  };
  let res: any = await withdrawPost(data);
  if (res.errno == 0) {
    ElNotification({
      position: "top-left",
      zIndex: 1015,
      message: t("layer.wallet.operationSuccessful"),
      type: "success"
    });
    // emit("showMoney", false);
    showBanckDeit.value = "bankDetails";
  }
};

let walletDetil: any = ref({}); // 提现详情
let walletMony: any = ref({});
let balance: any = ref("0");
let warningTip = ref("0"); // 0: 未锁定 1:已锁定 锁定不能提现
let banckNames = ref("");
let ticket = ref("");

const getTicket = (type: any) => {
  ticket.value = type;

  let data = {
    ticket: ticket.value,
    bank_card_id: selectVal.value + "",
    amount: String(walletInfo.value)
  };
  withdrawPreview(data).then((res: any) => {
    if (res.errno == 0) {
      walletInfo.value = "";
      showBanckDeit.value = "withdrawalAudit";
      previewData.value = res.data.info;
      withdrawalOnceToken.value = res.data.withdrawal_once_token;
    }
  });
};
const getAlterPwd = type => {
  showBanckDeit.value = type;
  emit("showMoney", true);
};

const changeBalance = () => {
  if (Number(walletInfo.value) > Number(balance.value)) {
    ElNotification({
      position: "top-left",
      zIndex: 1015,
      message: t("layer.wallet.withdrawableAmount"),
      type: "warning"
    });
    return false;
  }
  console.log(
    "Number(walletInfo.value) < Number(walletDetil?.once_min_limit)",
    Number(walletInfo.value),
    walletDetil.value.once_min_limit
  );

  if (Number(walletInfo.value) < Number(walletDetil.value.once_min_limit)) {
    ElNotification({
      position: "top-left",
      zIndex: 1015,
      message: t("layer.wallet.withdrawalLimitCannot"),
      type: "warning"
    });
    return false;
  }
  return true;
};

const setWalletClear = () => {
  emit("showMoney", true);
  showBanckDeit.value = "bankDetails";
  selectVal.value = "";
  walletInfo.value = "";
  getWalletMony();
  getBankcardList();
  warningTip.value = setWallet.banckDetails?.user_locked_info?.withdraw_locked;
  walletDetil.value = setWallet.banckDetails?.withdrawal_policy;
};

const changeInputVal = () => {
  walletInfo.value = walletInfo.value.replace(/[^\d]/g, "");

  // 1.当输入框的值大于最大提现余额时需要分两种情况
  if (
    Number(walletInfo.value) > parseFloat(walletDetil.value?.once_max_limit)
  ) {
    // 1.1 当余额小于最大提现金额时，输入框的值等于余额
    if (
      parseFloat(balance.value) < parseFloat(walletDetil.value?.once_max_limit)
    ) {
      walletInfo.value = Math.floor(parseFloat(balance.value));

      // 1.2 当余额大于最大提现金额时，输入框的值等于最大可提现金额
    } else {
      walletInfo.value = parseFloat(walletDetil.value?.once_max_limit);
    }
  }
};

const setBanckList = () => {
  showBanckDeit.value = "bankList";
  getBankcardList();
};

// 获取可提现余额
const getWalletMony = () => {
  balance.value = "";
  getPaymentWithdrawAmountInfo().then((res: any) => {
    if (res.errno == 0) {
      walletMony.value = res.data;
      // 使用说明：is_free==0:最大提现金额为可用金额、is_free==1:最大提现金额为余额
      if (res.data.is_free) {
        balance.value = res.data.balance;
      } else {
        balance.value = res.data.usable_amount;
      }
    }
  });
};

onMounted(() => {});

defineExpose({
  setWalletClear,
  setBanckList
});
</script>

<style lang="scss" scoped>
:deep(.el-input__wrapper) {
  color: #fff;
  background: #1f2937;
}
:deep(.el-input) {
  --el-input-focus-border: none !important;
  --el-input-border-color: none;
}
:deep(.el-input__inner) {
  color: #fff;
}
:deep(.el-input-group__prepend) {
  color: #fff;
  background-color: #1f2937;
}
:deep(.el-input.is-disabled .el-input__wrapper) {
  color: #fff;
  box-shadow: none;
  background-color: #1f2937;
}
:deep(.el-input-group__append) {
  color: #fff;
  box-shadow: none;
  background-color: #1f2937;
}
:deep(.el-select__wrapper) {
  color: #fff;
  background-color: #1f2937;
}

:deep(.el-select-dropdown__item) {
  color: #333333 !important;
}

.el-select-dropdown__item.selected {
  color: #b11515;
  background-color: #409eff;
}

:deep(.el-select__placeholder) {
  color: #fff;
}
.Warning {
  border-radius: 2px;
  border: dashed 1px #ff9203;
}
.overflow-wrap_text {
  white-space: normal;
  overflow-wrap: break-word;
  word-wrap: break-word; /* 兼容旧浏览器 */
  word-break: break-all;
}
</style>
<style lang="less">
.el-select__wrapper {
  border: 1px solid #426073;
  box-shadow: none !important;
}
//下拉框的背景色
.el-select-dropdown__item {
  background: #1f2937 !important;
}

//下拉框的链接小方块
.el-select-dropdown__item.is-active {
  background: #1f2937 !important;
}

//鼠标移动上去的选中色
.el-select-dropdown__item.hover,
//下拉框背景色
.el-popper.is-light.mySelectStyle {
  background-color: #1f2937 !important;
  border: 1px solid #426073 !important;
}

//下拉框的链接小方块
.mySelectStyle.el-popper[data-popper-placement^="bottom"]
  .el-popper__arrow::before {
  background: #1f2937 !important;
  border-top: 1px solid #426073 !important;
}

.el-tag.el-tag--info {
  color: #fff;
  background: #1a2c38 !important;
}
.el-icon .el-tag__close {
  color: #fff !important;
}
.mySelectStyle.el-popper[data-popper-placement^="top"]
  .el-popper__arrow::before {
  background: #1f2937 !important;
  border: 1px solid #1f2937 !important;
}

//鼠标移动上去的选中色
.mySelectStyle {
  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    color: #fff !important;
    background: #1475e1 !important;
  }

  //下拉框的文本颜色
  .el-select-dropdown__item {
    color: #8e97a6;
  }

  //选中之后的颜色
  .el-select-dropdown__item.selected {
    color: #fff !important;
    background: #2a77c6 !important;
  }
}
</style>
